export function createStore(reducer,fn){
  // reducer 是在我们触发 dispatch的时候执行的
  let state ;
  let listeners = [];
  let getState = function(){
      return JSON.parse(JSON.stringify(state))
  }
  let dispatch = function(action){
    // action : {type:'add',num:10}
    state = reducer(state,action)
    listeners.forEach(item=>item())

  }
  dispatch({})
  // state = reducer(state,{})
  let subscribe = function(f){
    listeners.push(f);
    return function(){
      listeners = listeners.filter(item=>item!=f)
    }
  }
  if(typeof fn =='function'){
    return fn(createStore)(reducer)
  }
  return {
    getState,
    dispatch,
    subscribe
  }
}

export function combineReducers(obj){
  return function(state={},action){
    Object.keys(obj).forEach(item=>{
      state[item] = obj[item](state[item],action)
    })
    return state
  }
}



export const compose = (...fns)=>(...arg)=>{
  let last = fns.pop();
  return fns.reduceRight((prev,next)=>{
    return next(prev)
  },last(...arg))
}

export function applyMiddleware(...middleware){
  return function(createStore){
    return function(reducer){
      let store = createStore(reducer);
      // let middle = middleware(store)
      let middles = middleware.map(item=>item(store))
      // item logger reduxThunk middles存储的时各个中间件的返回结果
      // let temp = middle(store.dispatch);
      // let temp ;
      // middles.forEach(item=>{
      //   temp = item(store.dispatch)
      // })
      let temp = compose(...middles)(store.dispatch)
      return {
        ...store,
        dispatch:temp
      }
    }
  }
}